<template>
    <div class="container">
        <div class="header-wrapper">
            <van-nav-bar :title="'修改' + titleFromRoute" left-arrow @click-left="onClickLeft">
                <template #right>
                    <van-button type="success" @click="onSave(phone)">保存</van-button>
                </template>
            </van-nav-bar>
        </div>
        <div v-if="titleFromRoute === '昵称'">
            <van-cell-group>
                <van-field v-model="nicknameValue" placeholder="请输入修改的昵称" />
            </van-cell-group>
        </div>
        <div v-else-if="titleFromRoute === '地址'">
            <van-cell-group>
                <van-field v-model="addressValue" placeholder="请输入修改的地址" />
            </van-cell-group>
        </div>
    </div>
</template>
<script setup>
import { ref} from 'vue';
import http from '@/http';
import { useRouter } from 'vue-router';
import { useRoute } from 'vue-router';

let show = ref(false);
const route = useRoute();
const router = useRouter();
let phone = localStorage.getItem('reginame');
let nicknameValue = ref('');
let addressValue = ref('');
let titleFromRoute = route.query.titleRoute;

const onSave = (phone) => {
    let newNickname = nicknameValue.value;
    let newAddress = addressValue.value;
    if (newNickname || newAddress) {
        let dataToSend = {};
        if (newNickname) {
            dataToSend['newNickname'] = newNickname;
        }
        if (newAddress) {
            dataToSend['newAddress'] = newAddress;
        }
        router.push({
            path: '/userinfo',
            query: dataToSend
        });

        let params = {
            nickname: newNickname,
            address: newAddress
        };

        http.put(`/patient/register_login/${phone}/`, params).then(res => {
            if (res.status === 200) {
                console.log('个人信息修改成功', res.data);
                show.value = true;
            }
        }).catch(err => {
            console.log('个人信息修改失败', err);
        });
    } else {
        console.log('没有输入要修改的值');
    }
};


const onClickLeft = () => {
    router.push('/userinfo');
};
</script>
<style scoped>
.container {
    height: 100vh;
    background-color: #faf8f8;
}

.header-wrapper {
    width: 100%;
}
</style>